snowsoft.gibay._LOG.info("Loading class, 'snowsoft.gibay.Find'");

/**
 * Calls GetSearchResults data service
 * Handles Find Tab UI updates
 * @author digitalghost.liu@gmail.com 
 */
jsx3.lang.Class.defineClass("snowsoft.gibay.Find", null, [], function(Find) {
	
	var PAGESIZE = 35;//pagesize for search item

	//data page split control varibles
	var _pageNum = 1;//start from 1 to totalpages.
	var _pageCount = 1;//total pages count;
	var _totalCount = 0;//total items count;

	//varible for determine the result items' search type,for example:categoryListings or keyword
	var _resultType = 'KEYWORDS';//CATEGORYLISTING,KEYWORDS
	var _resultCategoryData = null;//If the _resultType == 'CATEGORYLISTING',this varible means that which category the user would like to listing
	
	//shortcut to package
	var gibay = snowsoft.gibay;
	
	//private method : convert eBay's time into remaining time format
	var _convertRemainingTime = function(doc){
		var objRecs = doc.selectNodes("//record");
    	for(var i=0;i<objRecs.getLength();i++) {
      		var objRec = objRecs.getItem(i);
			if(objRec.getAttribute("EndTime") != ""){
				var remainingTimeStatus = "";
				var strStandard = objRec.getAttribute("EndTime").replace(/([0-9]+)-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})\.[0-9]*Z/g,'$1/$2/$3 $4:$5:$6');
				var endTime = Date.parse(strStandard);
				var nowTime = new Date().getTime();
				var timeSpan = endTime - nowTime;
				if(timeSpan<=0){
					remainingTimeStatus = "Ended";
				}else{
					var minutes = 1000 * 60;
					var hours = minutes * 60;
					var days = hours * 24;
					var years = days * 365;
					

					var d = parseInt(timeSpan/days);	
					var h = 0;
					var m = 0;
					var s = 0;
					timeSpan = (d!=0)?(timeSpan%days):timeSpan;
					h = parseInt(timeSpan/hours);
					timeSpan = (h!=0)?(timeSpan%hours):timeSpan;
					m = parseInt(timeSpan/minutes);
					timeSpan = (m!=0)?(timeSpan%minutes):timeSpan;
					s = parseInt(timeSpan/1000);
					
					remainingTimeStatus = (d!=0)?(remainingTimeStatus+d.toString()+' days '):remainingTimeStatus;
					remainingTimeStatus = (h!=0)?(remainingTimeStatus+h.toString()+':'):remainingTimeStatus;
					remainingTimeStatus = (m!=0)?(remainingTimeStatus+m.toString()+':'):remainingTimeStatus;
					remainingTimeStatus = (s!=0)?(remainingTimeStatus+s.toString()+''):remainingTimeStatus;

				}		
				objRec.setAttribute("RemainingTime",remainingTimeStatus);
			}
      	}
		
	};	

	//private method : update the page split link	
	var _updatePages = function(){

		var blkPageNav = gibay.APP.getJSXByName("blkPageNav");
		var html = '';
		if(_pageNum - 1 <= 0){
			html += '<span>&lt;Prev</span>';
		}else{
			html += '<a class="funclink" href="javascript:{void(0);}" onclick="snowsoft.gibay.Find.gotoPage('+(_pageNum-1)+')">&lt;Prev</a>';
		}
		html += '<span style="margin-left:4px;">|</span>';
		html += '<span style="margin-left:4px;margin-right:4px;">' + _pageNum + '&nbsp;of&nbsp;' + _pageCount + '&nbsp;pages&nbsp;'+_totalCount+'&nbsp;items</span>';
		html += '<span style="margin-right:4px;">|</span>';
		if(_pageNum + 1 > _pageCount){
			html += '<span>Next&gt;</span>';
		}else{
			html += '<a class="funclink" href="javascript:{void(0);}" onclick="snowsoft.gibay.Find.gotoPage('+(_pageNum+1)+')">Next&gt;</a>';
		}
		blkPageNav.setText(html,true);
		
	};
	
	//method for page navigation
	Find.gotoPage = function(pageNum){
		if(pageNum<1 || pageNum>_pageCount){
			return;
		}
		_pageNum = pageNum;
		//alert("goto page:"+_pageNum);
		Find.getItems(null);	
	};
	
	//method for user click top search button
	Find.doSearch = function(objEvent){
		_pageNum = 1;
		_pageCount = 1;
		_totalCount = 0;
		_resultType = 'KEYWORDS';
		_resultCategoryData = null;
		gibay.APP.getJSXByName("blkPriceFilter").setDisplay(jsx3.gui.Block.DISPLAYBLOCK,true);
		gibay._LOG.info("Do keyword search on keywords "+gibay.APP.getJSXByName("cmbKeywords").getValue());
		Find.getItems(objEvent);

	};

	//method for user click category to list the items in specifed category
	Find.categoryListing = function(objEvent){
		_pageNum = 1;
		_pageCount = 1;
		_totalCount = 0;
		_resultType = 'CATEGORYLISTING';	
		gibay.APP.getJSXByName("cmbKeywords").setValue('',true);
		gibay.APP.getJSXByName("blkPriceFilter").setDisplay(jsx3.gui.Block.DISPLAYNONE,true);
		_resultCategoryData = objEvent.categoryData;
		//alert(_resultType+":"+objEvent.categoryData.CategoryID);
		gibay._LOG.info("Get items belongs to category "+_resultCategoryData.CategoryID);
		Find.getItems(objEvent);
	};

	//method for user change list sort type
	Find.changeSortType = function(objEvent){
		_pageNum = 1;
		_pageCount = 1;
		_totalCount = 0;
		gibay._LOG.info("List sort type changes to "+gibay.APP.getJSXByName("selSortType").getValue());
		Find.getItems(objEvent);
	};

	//method for user change min price or max price
	Find.changePriceFilter = function(objEvent){
		_pageNum = 1;
		_pageCount = 1;
		_totalCount = 0;
		var objJSXMinPrice = gibay.APP.getJSXByName("txtMinPrice");
		var objJSXMaxPrice = gibay.APP.getJSXByName("txtMaxPrice");
		var minPrice = 0;
		var maxPrice = 0;
		if(objJSXMinPrice.getValue()!=objJSXMinPrice.getDefaultValue()&&(!isNaN(parseInt(objJSXMinPrice.getValue())))){
			minPrice = parseInt(objJSXMinPrice.getValue());
		}
		if(objJSXMaxPrice.getValue()!=objJSXMaxPrice.getDefaultValue()&&(!isNaN(parseInt(objJSXMaxPrice.getValue())))){
			maxPrice = parseInt(objJSXMaxPrice.getValue());
		}
		gibay._LOG.info("Price filter changed,min "+minPrice+",max "+maxPrice);
		Find.getItems(objEvent);
	};

	//method for user change the item list's view style
	Find.changeViewStyle = function(objEvent){
		var pValue = objEvent.previousValue;
		var value = objEvent.value;
		//alert("pre:"+pValue+",new:"+value);
		
		//there just 3 view style to swtich,pure list,list thumbnail compsite and thumbnail
		if(value >=66 ){//thumbnail list view
			value = 100;	
			gibay.APP.getJSXByName("blkListView").setDisplay(jsx3.gui.Block.DISPLAYNONE,true);	
			gibay.APP.getJSXByName("blkxThumbnailView").setDisplay(jsx3.gui.Block.DISPLAYBLOCK,true);	
			gibay.APP.getJSXByName("blkxThumbnailView").repaint();
		}else if(value>33 && value <60){//thumnail and list compsite view
			value = 50;	
			gibay.APP.getJSXByName("blkListView").setDisplay(jsx3.gui.Block.DISPLAYBLOCK,true);	
			gibay.APP.getJSXByName("mtxItems").setRowHeight(64);
			gibay.APP.getJSXByName("mcItemThumbnail").setDisplay(jsx3.gui.Block.DISPLAYBLOCK,true);	
			gibay.APP.getJSXByName("blkxThumbnailView").setDisplay(jsx3.gui.Block.DISPLAYNONE,true);	
		}else{//pure list view
			value = 0;	
			gibay.APP.getJSXByName("blkListView").setDisplay(jsx3.gui.Block.DISPLAYBLOCK,true);	
			gibay.APP.getJSXByName("mtxItems").setRowHeight(24);
			gibay.APP.getJSXByName("mcItemThumbnail").setDisplay(jsx3.gui.Block.DISPLAYNONE,true);	
			gibay.APP.getJSXByName("blkxThumbnailView").setDisplay(jsx3.gui.Block.DISPLAYNONE,true);	
		}	
		gibay.APP.getJSXByName("sliderViewStyle").setValue(value,true);	
		gibay._LOG.info("View style changed,slider value is "+value);

	};

	//method for fetch items about GUI arguments
	Find.getItems = function(objEvent){
			
		var objService = null;
		var suggestedKeyword = "";//keyword supplied for ebay to suggest realtive categories.	
		try{
			if(_resultType == 'KEYWORDS'){
				var keyword = gibay.APP.getJSXByName("cmbKeywords").getValue();	
				if(keyword == null || keyword == "")
					return;
				gibay.ModelManager.addPopularKeyword({jsxid:keyword,jsxtext:keyword});
				objService = gibay.APP.loadResource("getsearchresults_xml");
				objService.setOperation("GetSearchResults");
				objService.keywords = keyword;
				//code for process price filter
				var objJSXMinPrice = gibay.APP.getJSXByName("txtMinPrice");
				var objJSXMaxPrice = gibay.APP.getJSXByName("txtMaxPrice");
				var minPrice = 0;
				var maxPrice = 0;
				if(objJSXMinPrice.getValue()!=objJSXMinPrice.getDefaultValue()&&(!isNaN(parseInt(objJSXMinPrice.getValue())))){
					minPrice = parseInt(objJSXMinPrice.getValue());
				}
				if(objJSXMaxPrice.getValue()!=objJSXMaxPrice.getDefaultValue()&&(!isNaN(parseInt(objJSXMaxPrice.getValue())))){
					maxPrice = parseInt(objJSXMaxPrice.getValue());
				}
				objService.minPrice = minPrice;
				objService.maxPrice = maxPrice;

				gibay.APP.getJSXByName("lblResultType").setText('Results for keywords: '+objService.keywords,true);
				if(gibay.APP.getJSXByName("selSortType").getXMLId()!="MODEL_SortType_Keywords"){
					gibay.APP.getJSXByName("selSortType").setXMLId("MODEL_SortType_Keywords").repaint();	
					//codes for fix jsxselected attribute doesn't take effect with select component
					gibay.APP.getJSXByName("selSortType").setValue(gibay.APP.getCache().getDocument("MODEL_SortType_Keywords").selectNodes("//record").get(0).getAttribute("jsxid"));	
				}
				//suggested keyword here is the word user typed in textbox
				suggestedKeyword = keyword;
			}else if(_resultType == 'CATEGORYLISTING'){
				if(_resultCategoryData == null)
					return;
				objService = gibay.APP.loadResource("getcategorylistings_xml");
				objService.setOperation("GetCategoryListings");
				objService.categoryID = _resultCategoryData.CategoryID;	
				gibay.APP.getJSXByName("lblResultType").setText('Results for category: '+_resultCategoryData.CategoryName,true);
				if(gibay.APP.getJSXByName("selSortType").getXMLId()!="MODEL_SortType_CategoryListings"){
					gibay.APP.getJSXByName("selSortType").setXMLId("MODEL_SortType_CategoryListings").repaint();	
					//codes for fix jsxselected attribute doesn't take effect with select component
					gibay.APP.getJSXByName("selSortType").setValue(gibay.APP.getCache().getDocument("MODEL_SortType_CategoryListings").selectNodes("//record").get(0).getAttribute("jsxid"));	
				}
				//suggested keyword here is the category name user select to listing.
				suggestedKeyword = _resultCategoryData.CategoryName;
			}else{
				alert('invaild item listing type');
				return;
			}
			
			gibay.APP.getJSXByName("blkResultItems").showMask("Contracting ebay server to get item results...");
			objService.startTime = (new Date()).valueOf();	
			objService.pageSize = PAGESIZE;
			objService.pageNum = _pageNum;
			objService.sortType = gibay.APP.getJSXByName("selSortType").getValue();
			objService.subscribe(jsx3.net.Service.ON_SUCCESS,Find.onGetItemsSuccess);	
			objService.subscribe(jsx3.net.Service.ON_ERROR,Find.onGetItemsError);
			gibay._LOG.info("Call GetSearchResults service...");
			objService.doCall();
			//then get suggested categories from ebay service
			Find.getSuggestedCategories(suggestedKeyword);
		}catch(e){
			var objError = jsx3.lang.NativeError.wrap(e);
			gibay._LOG.error(objError.getMessage());	
		}


	};
	Find.onGetItemsSuccess = function(objEvent){
		var tTotal = ((new Date()).valueOf() - objEvent.target.startTime) / 1000;
		//alert(objEvent.target.getInboundDocument());
		gibay._LOG.info("Call GetSearchResults service successful.."+tTotal+" secs");
		
		var objDoc = gibay.APP.getCache().getDocument("MODEL_ResultItems");
		_convertRemainingTime(objDoc);
		//this code for live update time ticks,but cause some performace problem
		window.setInterval(function(){_convertRemainingTime(gibay.APP.getCache().getDocument("MODEL_ResultItems"));gibay.APP.getJSXByName("mtxItems").repaintData();},5000);

		//code for render page navigation	
		_pageCount = parseInt(objDoc.getAttribute("TotalNumberOfPages"));		
		_totalCount = parseInt(objDoc.getAttribute("TotalNumberOfEntries"));		
		_pageNum = 	parseInt(objDoc.getAttribute("PageNum"));
		_updatePages();

		gibay.APP.getJSXByName("blkResultItems").hideMask();

		//performance turning for render visible list only
		var value = gibay.APP.getJSXByName("sliderViewStyle").getValue();
		if(value >=66 ){//thumbnail list view
			gibay.APP.getJSXByName("blkxThumbnailView").repaint();
		}else{
			gibay.APP.getJSXByName("mtxItems").repaintData();
		}
	};
	Find.onGetItemsError = function(objEvent){
		var tTotal = ((new Date()).valueOf() - objEvent.target.StartTime) / 1000;
    	giaby._LOG.info("Get service error, 'Response':\n__________________\n" + objEvent.target.getInboundDocument() + "\n__________________\n response time: " + tTotal + " seconds.");
    	gibay.APP.getJSXByName("blkResultItems").hideMask();

	};

	//method for get suggested categories for current search
	Find.getSuggestedCategories = function(suggestedKeyword){
		try{
			var objService = gibay.APP.loadResource("getsuggestedcategories_xml");
			objService.setOperation("GetSuggestedCategories");
			objService.subscribe(jsx3.net.Service.ON_SUCCESS,Find.onGetSuggestedCategoriesSuccess);	
			objService.subscribe(jsx3.net.Service.ON_ERROR,Find.onGetSuggestedCategoriesError);
			objService.startTime = (new Date()).valueOf();	
			objService.suggestedKeyword = suggestedKeyword;
			gibay._LOG.info("Call getSuggestedCategories service....suggested keyword is "+suggestedKeyword);
			objService.doCall();
		}catch(e){
			var objError = jsx3.lang.NativeError.wrap(e);
			gibay._LOG.error(objError.getMessage());	
		}
	};
	Find.onGetSuggestedCategoriesSuccess = function(objEvent){
		var tTotal = ((new Date()).valueOf() - objEvent.target.startTime) / 1000;
		gibay._LOG.info("Call getSuggestCategories service successful.."+tTotal+" secs");
	};
	Find.onGetSuggestedCategoriesError = function(objEvent){
		var tTotal = ((new Date()).valueOf() - objEvent.target.StartTime) / 1000;
    	giaby._LOG.info("Get service error, 'Response':\n__________________\n" + objEvent.target.getInboundDocument() + "\n__________________\n response time: " + tTotal + " seconds.");
	};

	

});

//subscribe handler method to relevant events
snowsoft.gibay.APP.subscribe(snowsoft.gibay.Event.ON_SEARCH,snowsoft.gibay.Find.doSearch);
snowsoft.gibay.APP.subscribe(snowsoft.gibay.Event.ON_CATEGORYLISTING,snowsoft.gibay.Find.categoryListing);
snowsoft.gibay.APP.subscribe(snowsoft.gibay.Event.ON_SORTTYPE_CHANGES,snowsoft.gibay.Find.changeSortType);
snowsoft.gibay.APP.subscribe(snowsoft.gibay.Event.ON_PRICEFILTER_CHANGES,snowsoft.gibay.Find.changePriceFilter);
snowsoft.gibay.APP.subscribe(snowsoft.gibay.Event.ON_VIEWSTYLE_CHANGES,snowsoft.gibay.Find.changeViewStyle);

